""" 命令行应用的图形化界面 """

import subprocess
from clint.textui import colored, puts, prompt

from adb import adbutil, actions, fileparsers
from adb.connection import AdbConnection


class App(object):

    def __init__(self):
        self.pwd = '/sdcard'
        self.children = None
        self.socket = AdbConnection()

    def say_hi(self):
        puts(colored.green('Hello, This is Android command app:'))
        puts(colored.cyan('AllRight Reservered'))

    def start(self):
        print('检查ADB连接中...')
        self.check_adb()
        puts(colored.green('adb准备完成, 开始连接'))
        self.socket.connect()
        puts((colored.green('连接建立完成')))
        print('=' * 60 + '\n\n')
        try:
            while True:
                action = prompt.query(self.pwd + ': ')
                self.parse_action(action)
        except KeyboardInterrupt:
            pass
        puts(colored.green('\nbye'))

    def parse_action(self, action):
        if 'ls' == action:
            result = self.socket.send(actions.FileList(self.pwd))
            self.children = result.get('result')
            fileparsers.type_highlight(self.children)
        elif 'shell' == action:
            subprocess.run(['adb', 'shell'])
        elif 'exit' == action:
            puts(colored.green('\nbye'))
            exit(0)

    def check_adb(self):
        checks = [(adbutil.check_adb_path, 'Adb必须在PATH中'),
                  (adbutil.check_device_attached, '没有发现Android设备')]
        for check, comment in checks:
            if not check():
                puts('出现错误: ' + colored.red(comment))
        if adbutil.check_adb_forward():
            adbutil.check_adb_forward()
